package com.isunland.managesystem.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.adapter.CheckedOffAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CheckedOffList;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.RequisitionDetail;
import com.isunland.managesystem.entity.RequisitionTripOriginal;
import com.isunland.managesystem.utils.LogUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * Created by wu on 2016/4/8.
 * 已申请调休列表
 */
public class CheckedOfflistFragment extends BaseListFragment {
  public static final String EXTRA_CODES =
      "com.isunland.managesystem.ui.CheckedOfflistFragment.EXTRA_CODES";
  private ArrayList<CheckedOffList.ListContent> mlist = new ArrayList<CheckedOffList.ListContent>();
  private CheckedOffAdapter mAdapter;
  private String tripQuotesCode;//  关联差旅单id,带单引号,获取关联的差旅单
  private String btripListCode = "";//  选择的一条差旅单id
  private CurrentUser mUser;
  private BaseVolleyActivity mActivity;
  private ArrayList<RequisitionDetail> mTripList;
  private String[] tripNames;
  private ProgressDialog mdialog;

  @Override protected void isPostStart(boolean isPostStart, boolean isShowEmpty) {
    super.isPostStart(false, true);
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    // 设置返回图标
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    //        ( (BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.hasCheckOff);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle("");
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    tripQuotesCode = (String) getArguments().getSerializable(EXTRA_CODES);
    volleyPostTripe();
    super.onCreate(savedInstanceState);
  }

  private void volleyPostMenu(final String[] tripNames) {
    // 生成一个SpinnerAdapter
    ArrayAdapter<String> adapter =
        new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item,
            tripNames);

    // 得到ActionBar
    android.support.v7.app.ActionBar actionBar =
        ((BaseVolleyActivity) getActivity()).getSupportActionBar();
    // 将ActionBar的操作模型设置为NAVIGATION_MODE_LIST
    actionBar.setNavigationMode(android.support.v7.app.ActionBar.NAVIGATION_MODE_LIST);
    // 为ActionBar设置下拉菜单和监听器
    actionBar.setListNavigationCallbacks(adapter,
        new android.support.v7.app.ActionBar.OnNavigationListener() {
          @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) {
            btripListCode = mTripList.get(itemPosition).getId();
            volleyPost();
            return false;
          }
        });
  }

  private void volleyPostTripe() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.ULR_TRIP_LIST);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("regStaffId", mUser.getJobNumber());
    params.put("memberCode", mUser.getMemberCode());
    params.put("dataStatus", "checkPass");
    params.put("orderField", "REG_DATE");
    params.put("orderSeq", "desc");
    params.put("page", "1");
    params.put("rows", "1000");
    //查看已关联差旅单列表
    params.put("ids", tripQuotesCode);
    showDialog();
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        LogUtil.i("arg0==" + arg0);
        //查看已关联差旅单列表
        RequisitionTripOriginal original = new Gson().fromJson(arg0, RequisitionTripOriginal.class);
        ArrayList<RequisitionDetail> dataList = (ArrayList<RequisitionDetail>) original.getRows();
        if (mTripList == null) {
          mTripList = new ArrayList<RequisitionDetail>();
        }
        mTripList.clear();
        mTripList.addAll(dataList);
        tripNames = new String[mTripList.size()];
        for (int i = 0; i < mTripList.size(); i++) {
          tripNames[i] = mTripList.get(i).getBtripReason();
          LogUtil.i(" tripNames[i]===" + mTripList.get(i).getBtripReason());
        }
        btripListCode = mTripList.get(0).getId();
        volleyPost();
        //适配spinner
        volleyPostMenu(tripNames);
        dismissDialog();
      }
    });
  }

  @Override public String getUrl() {
    return ApiConst.URL_CHECKEDOFF_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("memberCode", CurrentUser.newInstance(getActivity()).getMemberCode());
    params.put("regStaffId", CurrentUser.newInstance(getActivity()).getJobNumber());
    params.put("remark", "可用调休申请");
    params.put("orderField", "ORDER_NO");
    params.put("dataStatus", "checkPass");
    params.put("orderSeq", "desc");
    params.put("dateFormat", "yyyy-MM-dd HH:mm:ss");
    params.put("btripListCode", btripListCode);
    return params;
  }

  @Override public void resolveResponse(String json) {
    CheckedOffList list = new Gson().fromJson(json, CheckedOffList.class);
    List<CheckedOffList.ListContent> contents = list.getRows();
    if (mlist == null) {
      mlist = new ArrayList<CheckedOffList.ListContent>();
    }
    mlist.clear();
    mlist.addAll(contents);
    setAdapter(mlist);
  }

  private void setAdapter(List<CheckedOffList.ListContent> mlist) {

    if (mAdapter == null) {
      mAdapter = new CheckedOffAdapter(getActivity(), mlist);
    }
    setListAdapter(mAdapter);
    ((CheckedOffAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    CheckedOffList.ListContent content = mAdapter.getItem(position - 1);
    Intent intent = new Intent(getActivity(), CheckedOffDetailActicity.class);
    intent.putExtra(CheckedOffdetailFragment.EXTRA_VALUE, content);
    startActivity(intent);
    super.onListItemClick(l, v, position, id);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 响应返回图标
      case android.R.id.home:

        //                if (NavUtils.getParentActivityName(getActivity()) != null) {
        //                    NavUtils.navigateUpFromSameTask(getActivity());
        //                }
        getActivity().finish();
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void showDialog() {
    mdialog = new ProgressDialog();
    // mdialog.setCancelable(false);//点击返回键dialog消失
    FragmentManager fm = getActivity().getSupportFragmentManager();
    mdialog.setTargetFragment(CheckedOfflistFragment.this, 0);
    mdialog.show(fm, "");
  }

  private void dismissDialog() {

    try {
      mdialog.dismiss();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static CheckedOfflistFragment newInstance(String tripQuotesCode) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_CODES, tripQuotesCode);
    CheckedOfflistFragment mFragment = new CheckedOfflistFragment();
    mFragment.setArguments(bundle);
    return mFragment;
  }
}
